package com.simafei.flow.core.data;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.map.MapUtil;
import com.simafei.flow.core.ExecutionContext;
import com.simafei.flow.core.ExecutionResult;
import com.simafei.flow.core.Node;
import com.simafei.flow.core.common.NodeType;
import lombok.EqualsAndHashCode;
import lombok.Setter;
import lombok.ToString;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author fengpengju
 */
@EqualsAndHashCode(callSuper = true)
@ToString
@Setter
public class StoreNode extends Node {

    private static final String AFFECT_ROWS_KEY = "_rows";

    private StoreSpec storeSpec;

    private DataManager dataManager;

    public StoreNode() {
        super(NodeType.DATA_MODIFY);
    }

    @Override
    protected List<ExecutionResult> doExecute(ExecutionContext context, List<Map<String, Object>> params) {
        List<Integer> rows = dataManager.saveOrUpdate(storeSpec, params);

        if (CollectionUtil.isEmpty(rows)) {
            return params.stream().map(param -> ExecutionResult.builder()
                    .inputParams(param)
                    .results(List.of())
                    .build()).collect(Collectors.toList());
        }
        List<ExecutionResult> results = new ArrayList<>();

        // 每一行执行影响的条数
        for (int i = 0; i < params.size(); i++) {
            results.add(ExecutionResult.builder()
                    .inputParams(params.get(i))
                    .results(List.of(MapUtil.of(AFFECT_ROWS_KEY, rows.get(i))))
                    .build());
        }
        return results;
    }
}
